package com.ucap.spyxmp.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.ucap.spyxmp.data.RestResultBuilder;
import com.ucap.spyxmp.data.YpgsprzPdfModel;
import com.ucap.spyxmp.data.YpjyxkzPdfModel;
import com.ucap.spyxmp.model.SpyxmpMailInfo;
import com.ucap.spyxmp.util.CommonUtil;
import com.ucap.spyxmp.util.LicensePdfUtil;
import com.ucap.util.Conts;
import com.ucap.util.DateTime;
import com.ucap.util.DateUtil;
import com.ucap.util.StringUtils;
import com.ucap.spyxmp.model.SpyxmpApplyItem;
import com.ucap.spyxmp.model.SpyxmpYpjyxkz;
import com.ucap.weixin.model.WxWsbsUser;
import com.ucap.wsbs.model.WxWsbsFile;

import java.util.Calendar;
import java.util.List;

/**
 * 药品经营许可证controller
 */
public class YpjyxkzController extends SpyxmpBaseController {

    private static String tableName = "SPYXMP_YPJYXKZ";
    public String retPath;

    @Before(Tx.class)
    public void save() throws Exception{

        SpyxmpApplyItem applyItem = this.getApplyItemCg();
        String sblsh = applyItem.getStr("SBLSH");
        System.out.println(sblsh);

        //保存申请主体信息
        applyItem.set("STATUS", "1");
        applyItem.set("MODIFYDATE", DateUtil.getCurrtentDateTime());
        applyItem.update();

        List<WxWsbsFile> wsbsFiles = WxWsbsFile.me.findFileListByTableNameAndUserId("SIGNATURE", this.getUserId());
        if(wsbsFiles.size() == 0){
            throw new Exception("未获取到签名数据");
        }
        WxWsbsFile.me.updateSblsh(sblsh, "SIGNATURE", this.getUserId());

        //保存申请表信息
        switch (getType()){
            case "1":
                this.saveBz(sblsh);
                break;
            default:
                this.saveZx(sblsh);
                break;
        }
        renderJson(RestResultBuilder.builder().success(applyItem).build());
    }

    /**
     * 补正数据保存
     * @param sblsh
     * @throws Exception
     */
    private void saveBz(String sblsh) throws Exception{

        List<WxWsbsFile> wsbsFiles = WxWsbsFile.me.findFileListByTableNameAndUserId(tableName, this.getUserId());
        if(wsbsFiles.size() == 0){
            throw new Exception("请上传作废证明");
        }
        WxWsbsFile.me.updateSblsh(sblsh, tableName, this.getUserId());

        SpyxmpYpjyxkz data = new SpyxmpYpjyxkz();
        data.set("ID", StringUtils.getUUID());
        data.set("APPLYID", sblsh);
        data.set("TYPE", getType());

        String[] bzlxArray = getParaValues("bzlx");
        if (bzlxArray != null && bzlxArray.length > 0) {
            data.set("BZLX", StringUtils.join(bzlxArray, ","));
        }

        data.set("XKZBH", getPara("xkzbh"));
        data.set("GFRZSBH", getPara("gfrzsbh"));
        data.set("ZFBLX", getPara("zfblx"));
        data.set("REASON", getPara("reason"));
        data.set("BZ", getPara("bz"));
        data.set("SMRQ", getParaToDate("smrq"));
        data.set("ADDTIME", DateUtil.getCurrtentDateTime());
        data.set("MODIFYDATE", DateUtil.getCurrtentDateTime());

        //如果补证药品经营许可证，则
        if(StringUtils.join(bzlxArray, ",").contains("1")){
            YpjyxkzPdfModel pdfModel = this.saveLicense(sblsh, data.getStr("ZFBLX"));
            data.set("QYMC", pdfModel.getQymc());
            data.set("ZCDZ", pdfModel.getZcdz());
            data.set("FDDBR", pdfModel.getFddbr());
            data.set("QYFZR", pdfModel.getQyfzr());
            data.set("ZLFZR", pdfModel.getZlfzr());
            data.set("CKDZ", pdfModel.getCkdz());
            data.set("JYFW", pdfModel.getJyfw());
            data.set("QFRQ", pdfModel.getQfrq());
            data.set("FZJG", pdfModel.getFzjg());
            data.set("YXQ", pdfModel.getYxq());
        }
        //如果补证药品经营质量监督证书，则
        if(StringUtils.join(bzlxArray, ",").contains("2")){

            YpgsprzPdfModel pdfModel = this.saveLicenseGsp(sblsh);
            data.set("GSP_QYMC", pdfModel.getQymc());
            data.set("GSP_DZ", pdfModel.getDz());
            data.set("GSP_RZFW", pdfModel.getRzfw());
            data.set("GSP_QFRQ", pdfModel.getQfrq());
            data.set("GSP_FZJG", pdfModel.getFzjg());
            data.set("GSP_YXQ", pdfModel.getYxq());
        }

        data.save();
    }

    /**
     * 注销数据保存
     * @param sblsh
     * @throws Exception
     */
    private void saveZx(String sblsh) throws Exception{

        String sfjbyj = getPara("sfjbyj");
        if("1".equals(sfjbyj)){
            //具备原件，填写邮寄地址
            SpyxmpMailInfo mailInfo = null;
            List<SpyxmpMailInfo> mailInfos = SpyxmpMailInfo.me.findByUserId(getUserId());
            if(mailInfos.size() > 0){
                mailInfo = mailInfos.get(0);
                mailInfo.set("NAME", getPara("yjr"));
                mailInfo.set("MOBILE", getPara("yjrdh"));
                mailInfo.set("ADDRESS", getPara("yjrdz"));
                mailInfo.set("MODIFYDATE", DateUtil.getCurrtentDateTime());
                mailInfo.update();
            }else{
                mailInfo = new SpyxmpMailInfo();
                mailInfo.set("ID", StringUtils.getUUID());
                mailInfo.set("USERID", getUserId());
                mailInfo.set("NAME", getPara("yjr"));
                mailInfo.set("MOBILE", getPara("yjrdh"));
                mailInfo.set("ADDRESS", getPara("yjrdz"));
                mailInfo.set("ADDTIME", DateUtil.getCurrtentDateTime());
                mailInfo.set("MODIFYDATE", DateUtil.getCurrtentDateTime());
                mailInfo.save();
            }
        }else{
            //上传遗失证明
            List<WxWsbsFile> wsbsFiles = WxWsbsFile.me.findFileListByTableNameAndUserId(tableName, this.getUserId());
            if(wsbsFiles.size() == 0){
                throw new Exception("请上传遗失证明");
            }
            WxWsbsFile.me.updateSblsh(sblsh, tableName, this.getUserId());
        }

        SpyxmpYpjyxkz data = new SpyxmpYpjyxkz();
        data.set("ID", StringUtils.getUUID());
        data.set("APPLYID", sblsh);
        data.set("TYPE", getType());
        data.set("XKZBH", getPara("xkzbh"));
        data.set("GFRZSBH", getPara("gfrzsbh"));
        data.set("SQRQ", getParaToDate("sqrq"));
        data.set("BZ", getPara("bz"));
        data.set("ADDTIME", DateUtil.getCurrtentDateTime());
        data.set("MODIFYDATE", DateUtil.getCurrtentDateTime());
        //添加邮寄信息
        data.set("SFJBYJ", sfjbyj);
        data.set("YJR", getPara("yjr"));
        data.set("YJRDH", getPara("yjrdh"));
        data.set("YJRDZ", getPara("yjrdz"));
        data.save();
    }

    @Before(Tx.class)
    private YpjyxkzPdfModel saveLicense(String sblsh, String zfblx) throws Exception {
        WxWsbsUser user = Conts.getSessionUser(getSession());

        //生成业务办理成功后的证照信息
        //获取证照信息
        if (getSession().getAttribute(CommonUtil.LICENSE_DATA) == null) {
            throw new Exception("没有获取到相关证件信息");
        }

        JSONObject xkzLicense = (JSONObject) getSession().getAttribute(CommonUtil.LICENSE_DATA);

        String ypjyxkzh = xkzLicense.getString("证号");
        String qymc = xkzLicense.getString("企业名称");
        String zcdz = xkzLicense.getString("注册地址");
        String fddbr = xkzLicense.getString("法定代表人");
        String qyfzr = xkzLicense.getString("企业负责人");
        String zlfzr = xkzLicense.getString("质量负责人");
        String ckdz = xkzLicense.getString("仓库地址");
        String jyfw = xkzLicense.getString("经营范围");
        String yxqxNow = xkzLicense.getString("有效期至");
        String[] yxqxArray = yxqxNow.split("-");
        String yxqn = yxqxArray[0];
        String yxqy = yxqxArray[1];
        String yxqr = yxqxArray[2];
        String fzjg = xkzLicense.getString("发证机关") != null ? xkzLicense.getString("发证机关") : "东莞市食品药品监督管理局";
        Calendar nowCalendar = Calendar.getInstance();
        /*String qfrqN = xkzLicense.getString("有效期始");
        String[] qfrqArray = qfrqN.split("-");
        String qfrqn = qfrqArray[0];
        String qfrqy = qfrqArray[1];
        String qfrqr = qfrqArray[2];*/



        String qfrqn = String.valueOf(nowCalendar.get(Calendar.YEAR));
        String qfrqy = String.valueOf(nowCalendar.get(Calendar.MONTH) + 1);
        String qfrqr = String.valueOf(nowCalendar.get(Calendar.DATE));


        YpjyxkzPdfModel pdfModel = new YpjyxkzPdfModel(ypjyxkzh, qymc, zcdz
                , fddbr, qyfzr, zlfzr, ckdz, jyfw, yxqn, yxqy, yxqr, fzjg, qfrqn, qfrqy, qfrqr);

        if("1".equals(zfblx)){
            //正本路径
            String licenseZbPath = LicensePdfUtil.generateYpjyxkzZb(pdfModel);

            try {

                WxWsbsFile licenseZb = new WxWsbsFile();
                licenseZb.set("ID", StringUtils.getUUID());
                licenseZb.set("SBLSH", sblsh);
                licenseZb.set("USERID", user.getStr("id"));
                licenseZb.set("FILEPATH", licenseZbPath);
                licenseZb.set("FILENAME", "药品经营许可证正本.png");
                licenseZb.set("CONTENTTYPE", "image/png");
                licenseZb.set("TABLENAME", "YPJYXKZ_ZB");
                licenseZb.set("ADDTIME", new DateTime().getTimestamp());
                licenseZb.set("ADDUSER", user.get("id"));
                licenseZb.set("UPDATETIME", new DateTime().getTimestamp());
                licenseZb.set("UPDATEUSER", user.get("id"));
                licenseZb.set("DATASTATE", "I");

                boolean isZbSave = licenseZb.save();

                if (!isZbSave) {
                    throw new Exception("保存药品经营许可证正本失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{

            //副本路径
            String licenseFbPath = LicensePdfUtil.generateYpjyxkzFb(pdfModel);


            try {

                WxWsbsFile licenseFb = new WxWsbsFile();
                licenseFb.set("ID", StringUtils.getUUID());
                licenseFb.set("SBLSH", sblsh);
                licenseFb.set("USERID", user.getStr("id"));
                licenseFb.set("FILEPATH", licenseFbPath);
                licenseFb.set("FILENAME", "药品经营许可证副本.png");
                licenseFb.set("CONTENTTYPE", "image/png");
                licenseFb.set("TABLENAME", "YPJYXKZ_FB");
                licenseFb.set("ADDTIME", new DateTime().getTimestamp());
                licenseFb.set("ADDUSER", user.get("id"));
                licenseFb.set("UPDATETIME", new DateTime().getTimestamp());
                licenseFb.set("UPDATEUSER", user.get("id"));
                licenseFb.set("DATASTATE", "I");

                boolean isFbSave = licenseFb.save();

                if (!isFbSave) {
                    throw new Exception("保存药品经营许可证副本失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return pdfModel;
    }

    @Before(Tx.class)
    private YpgsprzPdfModel saveLicenseGsp(String sblsh) throws Exception {
        WxWsbsUser user = Conts.getSessionUser(getSession());

        //生成业务办理成功后的证照信息
        //获取证照信息
        if (getSession().getAttribute(CommonUtil.LICENSE_DATA) == null) {
            throw new Exception("没有获取到相关证件信息");
        }

        JSONObject xkzLicense = (JSONObject) getSession().getAttribute(CommonUtil.LICENSE_DATA_GSP);

        String zsbh = xkzLicense.getString("证书编号");
        String qymc = xkzLicense.getString("企业名称");
        String dz = xkzLicense.getString("地址");
        String rzfw = xkzLicense.getString("认证范围");
        String yxqxNow = xkzLicense.getString("有效期至");
        String[] yxqxArray = yxqxNow.split("-");
        String yxqn = yxqxArray[0];
        String yxqy = yxqxArray[1];
        String yxqr = yxqxArray[2];
        String fzjg = xkzLicense.getString("发证机关") != null ? xkzLicense.getString("发证机关") : "东莞市食品药品监督管理局";
        Calendar nowCalendar = Calendar.getInstance();
        /*String qfrqN = xkzLicense.getString("有效期始");
        String[] qfrqArray = qfrqN.split("-");
        String qfrqn = qfrqArray[0];
        String qfrqy = qfrqArray[1];
        String qfrqr = qfrqArray[2];*/



        String qfrqn = String.valueOf(nowCalendar.get(Calendar.YEAR));
        String qfrqy = String.valueOf(nowCalendar.get(Calendar.MONTH) + 1);
        String qfrqr = String.valueOf(nowCalendar.get(Calendar.DATE));


        YpgsprzPdfModel pdfModel = new YpgsprzPdfModel(zsbh, qymc, dz
                , rzfw, yxqn, yxqy, yxqr, fzjg, qfrqn, qfrqy, qfrqr);
        //正本路径
        String licenseGspPath = LicensePdfUtil.generateYpGspRzzs(pdfModel);

        try {

            WxWsbsFile licenseZb = new WxWsbsFile();
            licenseZb.set("ID", StringUtils.getUUID());
            licenseZb.set("SBLSH", sblsh);
            licenseZb.set("USERID", user.getStr("id"));
            licenseZb.set("FILEPATH", licenseGspPath);
            licenseZb.set("FILENAME", "药品经营质量管理规范认证证书.png");
            licenseZb.set("CONTENTTYPE", "image/png");
            licenseZb.set("TABLENAME", "GSP");
            licenseZb.set("ADDTIME", new DateTime().getTimestamp());
            licenseZb.set("ADDUSER", user.get("id"));
            licenseZb.set("UPDATETIME", new DateTime().getTimestamp());
            licenseZb.set("UPDATEUSER", user.get("id"));
            licenseZb.set("DATASTATE", "I");

            boolean isZbSave = licenseZb.save();

            if (!isZbSave) {
                throw new Exception("保存药品经营质量管理规范认证证书失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return pdfModel;
    }

    public void getData(){

    }

    public YpjyxkzController() {
        super(tableName);
    }
}
